package com.desire.homework;

import java.util.stream.IntStream;
import java.util.stream.Stream;

/**
 * @author desire
 */
public class _47_求1到100的和 {
    public static int num = 0;

    public static void main(String[] args) {
        // for 循环
        int sum = 0;
        for (int i = 0; i <= 100; i++) {
            sum += i;
        }
        System.out.println(sum);

        // 递归
        int sum2 = sum(100);
        System.out.println("1+2+3+...+100=" + sum2);

        //java8 IntStream.rangeClosed()
        int sum3 = IntStream.rangeClosed(1, 100).sum();
        System.out.println("1+2+3+...+100=" + sum3);

        //  Stream.iterate
        var n2 = Stream.iterate(1, a -> a + 1).limit(100);
        System.out.println(n2.reduce(Integer::sum).get());
    }

    public static int sum(int i) {
        num += i--;
        if (i == 0) {
            return num;
        } else {
            return sum(i);
        }
    }
}
